package com.my.vote.pst.user;

import android.text.TextUtils;

import com.my.vote.VoteApplication;
import com.my.vote.entity.EUser;
import com.my.vote.entity.req.ReqLogin;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.RxBusEventManager;
import com.sfh.lib.mvp.service.AbstractPresenter;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

/**
 * 功能描述:登录
 *
 * @author
 * @date 2018/4/12
 */
public class PstLogin extends AbstractPresenter<IPstLogin.IVLogin> implements IPstLogin {
    @Override
    public void login(final ReqLogin login) {

        if (login == null) {
            getView().showToast("Please fill in the relevant user information!");
            return;
        }
        if (TextUtils.isEmpty(login.getNumber())) {
            getView().showToast("Please enter the account number!");
            return;
        }
        if (TextUtils.isEmpty(login.getPwd())) {
            getView().showToast("Please input a password!");
            return;
        }
        this.getView().showLoading(false);
        BmobQuery<EUser> query = new BmobQuery<>();
        query.addWhereEqualTo("account", login.getNumber());
        query.addWhereEqualTo("password", login.getPwd());
        query.findObjects(AppCacheManager.getApplication(), new FindListener<EUser>() {
            @Override
            public void onSuccess(List<EUser> list) {
                getView().hideLoading();
                if (list != null && !list.isEmpty()) {
                    // 保存用户信息
                    AppCacheManager.newInstance().putCache(true, VoteApplication.USER, list.get(0));
                    if (login.isSavePwd()) {
                        // 保存账号
                        AppCacheManager.newInstance().putCache(true, VoteApplication.ACCOUNT, login.getNumber());
                    }
                    RxBusEventManager.postEvent(list.get(0));
                    getView().onSuccess();

                } else {
                    getView().onError("User does not exist!");
                }
            }

            @Override
            public void onError(int i, String s) {
                getView().hideLoading();
                getView().onError("User does not exist!");
            }
        });
    }
}
